<?php
class Custom_Controller_Plugin_Zip extends Zend_Controller_Plugin_Abstract
{
	private $target='';
	private $source='';
	private $files=array();
	private $suffix=array('jpeg','jpg','gif','png');

	function __construct($source,$suffix=null,$target=null) 
	{
		$this->folder=new Custom_Controller_Plugin_Folder();
		if($source&&file_exists($source)){
			$zip=$this->folder->getSuffix($source);
			if($zip!='zip'){
				return false;
			}else{
				$this->source=$source;
			}
		}else{
			return false;
		}
		
		if($suffix!==null){
			$this->suffix=$suffix;
		}
		
		if($target!==null){ 
			$this->target=$target;
		}else{
			$this->target=PROJECT_ROOT.DS.'data'.DS.'tmp'.DS.'zip'.DS.md5(time());
		}
		
		if (!is_dir($this->target)){
    		$this->folder->createDir($this->target);
    	}
	}
	
	//解压并返回所有指定文件路径
    public function deCompression($rename=false)
    {
        $zip = new ZipArchive;
        if ($zip->open($this->source)===true){
            $zip->extractTo($this->target);
            $zip->close();
            if($this->suffix){
				$allfile=$this->folder->listFile($this->target,'file');
				if(is_array($allfile))foreach($allfile as $key=>$val){
					 $suffix=$this->folder->getSuffix($val);
					 if(in_array($suffix,$this->suffix)){ 
					 	if($rename){
					 		if(copy($val, $this->target.DS.$key.'.'.$suffix)){
					 			$this->files[] =md5(time()).'/'.$key.'.'.$suffix;
					 		}
					 	}else{
							$this->files[] =$val;
					 	}
					 }
				}
            }else{
            	$this->files=$this->folder->listFile($this->target);
            }
			return $this->files;
        }else{
        	return false;
        }
       
    }
    
	//打包压缩
    public function compression()
    {
        $zip = new ZipArchive;
        if ($zip->open($this->target, ZipArchive::CREATE) === true){
            foreach ($this->source as $item)
                if (file_exists($item))
                    $this->addZipItem($zip, realpath(dirname($item)).DS, realpath($item).DS);
            $zip->close();
            return true;
        }
        return false;
    }
    
	
   
}